package com.mamingchao.concurrent.Lock.LockOptimize;

import java.util.concurrent.TimeUnit;

/**
 * m1 --> m2 锁细化优化
 * m3 --> m4 锁粗化优化
 * Created by mamingchao on 2020/10/29.
 */
public class FineCoarseLock {
    int count;

    synchronized void m1() {
        // do sth which need not sync
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //业务逻辑中只有 这一句需要sync
        count ++;

        // do sth which need not sync
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    void m2() {
        // do sth which need not sync
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        synchronized (this) {
            count ++;
        }

        // do sth which need not sync
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    void m3() {
        // do sth which need sync
        synchronized (this) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        synchronized (this) {
            count++;
        }

        synchronized (this) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    synchronized void m4() {
        // do sth which need sync
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        count++;

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
